//app.js
var amapFile = require('libs/amap-wx.js'); //如：..­/..­/libs/amap-wx.js
 var myAmapFun = new amapFile.AMapWX({
      key: '55e2591136e5d5aec54c9b1de500014e'
    });

App({


  onLaunch: function() {

    let that = this
    // 在这里用定时器模拟网络请求的过程
    // setTimeout(function () {
    //   that.globalData.position = 'pxh'
    // }, 3000) 

    // wx.login({
    //   success: res => {
    //     console.log("获取code");
    //     console.log(res);
    //     // 发送 res.code 到后台换取用户token
    //     wx.request({
    //       url: this.globalData.url + '/app-users/userlogin',
    //       method: 'POST',
    //       header: {
    //         'content-type': 'application/x-www-form-urlencoded'
    //       },
    //       data: {
    //         code: res.code
    //       },
    //       success: res => {
    //         // 获取到用户的token，存储在本地
    //         console.log('app调用成功');
    //         console.log(res);
    //         wx.setStorageSync('id_token', res.data.idToken);
    //         wx.setStorageSync('open_id', res.data.userDTO.login);
    //         this.globalData.state = res.data.userDTO.authorities;
    //         wx.setStorageSync('authorities', res.data.userDTO.authorities);
    //         console.log(this.globalData)
    //         // 创建Socket
    //         wx.connectSocket({
    //           url: 'ws://localhost:8080/ws/asset',
    //           header: {
    //             'Authorization': 'Bearer ' + res.data.idToken
    //           },
    //           success: function(ws_res) {
    //             console.log('WebSocket连接创建', ws_res);

    //           },
    //           fail: function(err) {
    //             wx.showToast({
    //               title: '网络异常！',
    //             })
    //             console.log(err)
    //           },
    //         })

    //       }
    //     });
    //   }
    // });


    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {

          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              console.log(res);
              this.globalData.userInfo = res.userInfo
              wx.setStorageSync('userInfo', res.userInfo);
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              console.log(wx.getStorageSync('id_token'));
              wx.request({
                url: this.globalData.url + '/app-users/wechatname',
                method: 'PUT',
                header: {
                  'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  open_id: wx.getStorageSync('open_id'),
                  wechatname: wx.getStorageSync('userInfo').nickName,
                  headimage: wx.getStorageSync('userInfo').avatarUrl
                },
                success: res => {}
              });
            }
          })
        }
      }
    });

  },
  // 这里这么写，是要在其他界面监听，而不是在app.js中监听，而且这个监听方法，需要一个回调方法。
  watch: function(method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "position", {
      configurable: true,
      enumerable: true,
      set: function(value) {
        this._position = value;
        console.log('是否会被执行2')
        method(value);
      },
      get: function() {
        // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData.name的时候，这里就会执行。
        return this._position
      }
    })
  },
  warnwatch: function(method) {
    var obj = this.globalData;
    Object.defineProperty(obj, "warning", {
      configurable: true,
      enumerable: true,
      set: function(value) {
        this._warning = value;
        console.log('是否会被执行1')
        method(value);
      },
      get: function() {
        // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData.name的时候，这里就会执行。
        return this._warning
      }
    })
  },
  globalData: {
    userInfo: null,
    // url: 'http://localhost:8080/api',
    url: 'https://www.cheerylab.cn/api',
    //存储实时位置计时器
    setSSInter: '',
    //存储监控位置计时器
    setJKInter: '',
    _position: '',
    _warning: '',
    isfirst: true


  },
  //当小程序启动，或从后台进入前台显示，会触发 onShow
  onShow: function(options) {
    console.log("执行show方法")
    this.updateWebsockey();
    this.guestGetIsdoingTask();
    console.log(options)

  },
  //当小程序从前台进入后台，会触发 onHide
  onHide: function() {
    console.log('App onHide');
    let that = this;
    that.endSSSetInter();
    that.endJKSetInter();
    wx.closeSocket();
    // wx.onSocketOpen(function(res) {
    //   console.log(res);
    //   wx.closeSocket();
    // })
    wx.onSocketClose(function(res) {
      console.log('WebSocket 已关闭！')
    })

  },
  //当小程序发生脚本错误，或者 api 调用失败时
  onError: function() {
    let that = this;
    that.endSSSetInter();
    that.endJKSetInter();
    console.log('App onError');

  },
  updateWebsockey: function() {
    
    var that = this;
    return new Promise(function(resolve, reject) {
      wx.onSocketMessage(function(message) {
        //  console.log(message);
        var obj = JSON.parse(message.data);
        console.log(obj);
        resolve(obj);
        console.log(that.globalData);
        
          //更新session_id
          wx.request({
            url: that.globalData.url + '/app-users/websocket',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              open_id: wx.getStorageSync('open_id'),
              session_id: obj.session_id
            },
            success: res => {
              console.log("更新session_id成功")
            }
          })
        

        if (obj.message.indexOf("开启查看实时位置") > -1) {
          that.startSSSetInter(obj.message);
        } else if (obj.message.indexOf("关闭查看实时位置") > -1) {
          that.endSSSetInter();
        } else if (obj.message.indexOf("开启任务id") > -1) {

          that.startJKSetInter(obj.message);

        } else if (obj.message.indexOf("结束任务id") > -1) {
          that.endJKSetInter();
        } else if (obj.message.indexOf("发送位置") > -1) {
          that.globalData.position = obj.message.split(";")[1];
        } else if (obj.message.indexOf("超出安全区域") > -1) {
          that.globalData.warning = obj.message;
          wx.showTabBarRedDot({
            index: 1
          })
        } else if (obj.message.indexOf("您已超出安全范围") > -1) {
          console.log(obj.message)
          wx.showModal({
            title: '注意！',
            content: obj.message,
            confirmText: "我知道了",
            showCancel: false,
            success: function(res) {
              console.log(res);
              if (res.confirm) {
                console.log('用户点击主操作')
              } else {
                console.log('用户点击辅助操作')
              }
            }
          });
        }
      });

    });

  },
  //开启实时位置发送
  startSSSetInter: function(message) {
    var that = this;
    //将计时器赋值给setInter
    that.globalData.setSSInter = setInterval(
      function() {
        myAmapFun.getRegeo({
          success(res) {
            console.log(res)
            const latitude = res[0].latitude;
            const longitude = res[0].longitude;
            //发送自己的位置信息
            var admin_open_id = message.split(";")[0];
            wx.request({
              url: that.globalData.url + '/temporary-positions/send',
              method: 'POST',
              header: {
                'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                admin_open_id: admin_open_id,
                position_x: latitude,
                position_y: longitude
              },
              success: res => {
                console.log("发送实时位置信息成功");
              }
            })
          }
        })
      }, 5000);
  },
  //结束实时位置发送
  endSSSetInter: function() {
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.globalData.setSSInter);
  },

  //开启监控位置发送
  startJKSetInter: function(message) {
    var that = this;
    //将计时器赋值给setInter
    that.globalData.setJKInter = setInterval(
      function() {
        myAmapFun.getRegeo({
          success(res) {
            console.log(res)
            const latitude = res[0].latitude;
            const longitude = res[0].longitude;
            const speed = res.speed;
            const accuracy = res.accuracy;
            var taskId = message.split(":")[1];
            //发送自己的位置信息
            wx.request({
              url: that.globalData.url + '/task-details',
              method: 'POST',
              header: {
                'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                task_id: taskId,
                position_x: latitude,
                position_y: longitude
              },
              success: res => {
                console.log("发送监控位置信息成功");
              }
            })
          }
        })
      }, 5000);
  },
  //结束监控位置发送
  endJKSetInter: function() {
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.globalData.setJKInter);
  },

  //被监控人查看是否有正在进行的监控任务
  guestGetIsdoingTask: function() {
    let that = this;
    wx.request({
      url: this.globalData.url + '/check-tasks/guestisdoing',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('id_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        guest_open_id: wx.getStorageSync('open_id')
      },
      success: res => {
        console.log("被监控人查看否有正在进行的监控任务");
        console.log(res)
        if (res.data > 0) {
          that.startJKSetInter("开启任务id:" + res.data);
        }
      }
    });


  }



})